package com.seeTools.next.controller.sys;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.seeTools.next.common.tools.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

import static com.seeTools.next.bo.sys.SysConstant.CACHE_CAPTCHA_KEY_PREFIX;

/**
 * 验证码控制器
 *
 * @author xiaotong
 */
@Slf4j
@Controller
public class CaptchaController {

    @Resource
    private RedisUtil redisUtil;

    /**
     * 把校验码存储到session
     *
     * @param request  request
     * @param response response
     * @throws Exception 异常
     */
    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 4);
        String code = lineCaptcha.getCode();
        log.debug("gen captcha code:{}", code);
        code = code.toLowerCase();
        redisUtil.set(CACHE_CAPTCHA_KEY_PREFIX + code, code, 1, TimeUnit.MINUTES);
        lineCaptcha.write(response.getOutputStream());
    }
}
